/*
 * Copyright (C) Jochen Hiller, Bernd Kolb.
 * 
 * Licensed under Apache 2.0.
 * See http://www.apache.org/licenses/LICENSE-2.0
 */
package demo.geolocation;

import java.io.IOException;
import java.util.List;

import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;

// TODO make in background thread

public class MyGeoDecoder {

	private Geocoder geodecoder;

	public MyGeoDecoder(Context context) {
		geodecoder = new Geocoder(context);
	}

	public String getNameForLocation(Location loc) {
		String name = "<not found>";
		try {
			List<Address> locations = geodecoder.getFromLocation(loc
					.getLatitude(), loc.getLongitude(), 1);
			if (locations.size() > 0) {
				name = getReadableAddress(locations.get(0));
			}
			return name;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return name;
	}

	private String getReadableAddress(Address address) {
		// display(address.toString());
		StringBuilder builder = new StringBuilder();
		for (int i = 0; i < address.getMaxAddressLineIndex(); i++) {
			builder.append(address.getAddressLine(i));
			builder.append(' ');
		}
		return builder.toString();
	}

}

